package com.example.demo.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    public boolean sendSms(String phoneNumber, String templateParam) throws ClientException {
        // 设置阿里云短信服务的区域信息
        DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen", accessKeyId, accessKeySecret);
        IAcsClient client= new DefaultAcsClient(profile);

        // 创建请求对象
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(signName);
        request.setRegionId("cn-hangzhou");
        request.setTemplateCode(templateCode);
        request.setPhoneNumbers(phoneNumber);
        request.setTemplateParam(templateParam);

        try {
            // 发送短信
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            System.out.println("Response Code: " + response.getCode());
            System.out.println("Response Message: " + response.getMessage());
            // 如果返回的 JSON 数据包含 "Code": "OK"，则表示短信发送成功
            return response.getCode().contains("OK");
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            return false;
        }
    }
}

